package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Client;
import cn.wolfcode.crm.domain.IntegralItem;
import cn.wolfcode.crm.mapper.ClientMapper;
import cn.wolfcode.crm.mapper.IntegralItemMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IIntegralItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class IntegralItemServiceImpl implements IIntegralItemService {
    @Autowired
    private IntegralItemMapper integralItemMapper;
    @Autowired
    private ClientMapper clientMapper;


    public IntegralItem selectByPrimaryKey(Long id) {
        return integralItemMapper.selectByPrimaryKey(id);
    }

    public List<IntegralItem> selectAll() {
        return integralItemMapper.selectAll();
    }


    public PageResult query(QueryObject qo) {
        int total = integralItemMapper.selectCount();
        if(total==0){
            return new PageResult(total, Collections.EMPTY_LIST);
        }
        List<IntegralItem> rows = integralItemMapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    public void save(IntegralItem item) {
        //保存自己
        integralItemMapper.insert(item);
        //改变会员中的积分值
        Long clientId = item.getClient().getId();
        Client client = clientMapper.selectByPrimaryKey(clientId);
        int sum = Integer.sum(client.getIntegral(), item.getChangeIntegral());
        client.setIntegral(sum);
        clientMapper.updateIntegral(client);
    }

}
